<template>
  <h1>计算器练习</h1>
  <input type="text" v-model="num1" placeholder="请输入数字1"><br>
  <input type="text" v-model="num2" placeholder="请输入数字2"><br>
  <button @click="calc('+')">加</button>
  <button @click="calc('-')">减</button>
  <button @click="calc('*')">乘</button>
  <button @click="calc('/')">除</button>
  <hr>
  <h4>运算结果：{{res}}</h4>
</template>

<script setup>
import {ref} from "vue";

const num1 = ref('');
const num2 = ref('');
const res = ref('');
const calc = (op)=>{
  //res.value = eval(num1.value +op+ num2.value);

  let n1 =parseFloat(num1.value);
  let n2 =parseFloat(num2.value);
  if(isNaN(n1) || isNaN(n2)){
    alert("请输入数字");
  }
  switch (op) {
    case '+':
      res.value = n1+n2;break;
      break;
    case '-':
      res.value = n1-n2;break;
      break;
    case '*':
      res.value = n1*n2;break;
      break;
    case '/':
      if (n2==0){
        alert("除数不能为0");
        return;
      }else {
        res.value = n1/n2;
      }
  }
}



</script>


<style scoped>

</style>